package cn.gp.controller;

import cn.gp.common.PageInfo;
import cn.gp.common.R;
import cn.gp.entity.Category;
import cn.gp.service.CategoryService;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @ClassName CategoryController
 * @Description TODO
 * @Author He_Guoping
 * @Date 2023/5/26 22:27
 * @Version 1.0
 */
@Log4j
//@CrossOrigin("*")
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     *@Description 条件分页
     *@param page
     *@Param pageSize
     *@Param name 可选参数，前端经过处理
     *@Return cn.gp.common.R<cn.gp.common.PageInfo<cn.gp.entity.Category>>
     *@Author He_Guoping
     *@Date 12:54 2023/5/28
     */
    @GetMapping("/page")
    public R<PageInfo<Category>> page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam("name") String name) {
        log.info("page, pageSize" + page + " " + pageSize);
        log.info("name: " + name);
        return R.success(categoryService.page(page, pageSize, name));
    }

    /**
     *@Description 按照分类id删除
     *@param id
     *@Return cn.gp.common.R<java.lang.String>
     *@Author He_Guoping
     *@Date 12:56 2023/5/28
     */
    @DeleteMapping("del/{id}")
    public R<String> del(@PathVariable Integer id) {
        log.info("del " + id);
        return categoryService.delete(id) ? R.success("success") : R.error("error");
    }

    /**
     *@Description 添加分类
     *@param category
     *@Return cn.gp.common.R<java.lang.String>
     *@Author He_Guoping
     *@Date 12:57 2023/5/28
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody Category category) {
        log.info("add: " + category);
        return categoryService.add(category) ? R.success("success") : R.error("error");
    }

    /**
     *@Description 修改分类
     *@param category
     *@Return cn.gp.common.R<java.lang.String>
     *@Author He_Guoping
     *@Date 12:57 2023/5/28
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody Category category) {
        log.info("update: " + category);
        return categoryService.update(category) ? R.success("success") : R.error("error");
    }

    @GetMapping("/categoryList")
    public R<List<Category>> getCategoryList() {
        return R.success(categoryService.getCategoryList());
    }
}
